package com.roc.pan.download;

import com.google.common.collect.Lists;
import com.roc.pan.config.ConfigUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.List;

/**
 * @author roc
 * @date 2023/2/9
 */
@Slf4j
public class FileUtils {

    private List<String> existFileList = Lists.newArrayList();

    public FileUtils() {
        readExistFiles();
    }

    public void download() {
        List<String> urls = initUrls();
        for (String url : urls) {
            if (StringUtils.isBlank(url)) {
                continue;
            }
            try {
                if (!existFileList.contains(FileDownloader.getFileNameFromUrl(url))) {
                    FileDownloader.downloadFile(url, ConfigUtils.getConfig().getSaveFilePath());
                }
            } catch (Exception e) {
                try {
                    log.error("文件{}处理失败，错误：{}", FileDownloader.getFileNameFromUrl(url), e.getMessage());
                } catch (UnsupportedEncodingException unsupportedEncodingException) {
                    unsupportedEncodingException.printStackTrace();
                }
            }
        }

    }

    private void readExistFiles() {
        File file = new File(ConfigUtils.getConfig().getSaveFilePath());
        for (File subFile : file.listFiles()) {
            if (!subFile.getName().contains(FileDownloader.TEMP_SUFFIX)) {
                existFileList.add(subFile.getName());
            }
        }
    }

    private List<String> initUrls() {
        List<String> urlList = Lists.newArrayList();
        String filePath = ConfigUtils.getConfig().getDownloadResource();
        File file = new File(filePath);
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                urlList.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return urlList;
    }
}
